import json

from rest_framework import serializers
from carts.models import CartRe
from goods.models import Goods, GoodsCategory, Banner, HotSearchWords, DiscountPackage, SearchAd, \
    GoodsBannerImage, GoodsDescImage, Brand, GoodsAttribute


def time_format():
    """时间格式化"""
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    update_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    return create_time, update_time


class CategorySerializer(serializers.ModelSerializer):
    """首页导航分类"""

    class Meta:
        model = GoodsCategory
        fields = ["id", "name", "image", "is_index", ]


class GoodsBannerImageSerializer(serializers.ModelSerializer):
    """商品详情页轮播图"""
    goods_id = serializers.IntegerField(label='商品id', write_only=True)
    banner_list = serializers.ListField(child=serializers.FileField(), write_only=True, label='图片列表')
    banner_image = serializers.ImageField(read_only=True, label='轮播图片')

    class Meta:
        model = GoodsBannerImage
        exclude = ["create_time", "update_time", "goods"]

    def create(self, validated_data):
        banner_list = validated_data.get('banner_list')
        validated_data.pop('banner_list')
        result = []
        for banner in banner_list:
            validated_data['banner_image'] = banner
            instance = super().create(validated_data)
            result.append(instance)
        return result


class GoodsDescImageSerializer(serializers.ModelSerializer):
    """商品详情页详情图"""
    goods_id = serializers.IntegerField(required=True, label='商品id', write_only=True)
    desc_image = serializers.ImageField(read_only=True, label='商品详情图')
    desc_list = serializers.ListField(child=serializers.FileField(), label='商品详情列表', write_only=True)

    class Meta:
        model = GoodsDescImage
        exclude = ["create_time", "update_time", "goods"]

    def create(self, validated_data):
        desc_list = validated_data.get('desc_list')
        validated_data.pop('desc_list')
        result = []
        for desc in desc_list:
            validated_data['desc_image'] = desc
            instance = super().create(validated_data)
            result.append(instance)
        return result


class GoodsBrandSerializer(serializers.ModelSerializer):
    """商品品牌"""

    class Meta:
        model = Brand
        fields = ["id", "name"]


class GoodsIndexSerializer(serializers.ModelSerializer):
    """首页分类显示"""

    class Meta:
        model = Goods
        fields = ["id", "name", "goods_front_image", "market_price", "shop_price"]


class GoodsColorSerializer(serializers.ModelSerializer):
    """商品颜色"""
    # PrimaryKeyRelatedField 此字段将被序列化为关联对象的主键。
    goods_id = serializers.PrimaryKeyRelatedField(label='商品', read_only=True)

    class Meta:
        model = GoodsAttribute
        fields = ["id", "goods_id", "color", ]


class GoodsAttributeSerializer(serializers.ModelSerializer):
    """商品属性"""
    goods_code = serializers.CharField(label='商品编码', read_only=True)
    color = serializers.CharField(label='商品颜色', read_only=True)
    image = serializers.ImageField(label='属性图片', read_only=True)
    size = serializers.CharField(label='商品规格', read_only=True)
    weight = serializers.CharField(label='商品编码', read_only=True)
    price = serializers.CharField(label='商品编码', read_only=True)
    storage_amout = serializers.CharField(label='商品编码', read_only=True)
    attr_list = serializers.ListField(label='属性列表', write_only=True)
    img_list = serializers.ListField(child=serializers.ImageField(), label='属性对应的图片', write_only=True, allow_null=True)

    class Meta:
        model = GoodsAttribute
        exclude = ["create_time", "update_time", "goods", "is_delete"]

    def processing_data(self, receive_data):
        # 处理接收到的参数
        attr_list = receive_data.get('attr_list')
        img_list = receive_data.get('img_list')
        # 将字符串转换成json
        attr_list = [json.loads(attr) for attr in attr_list]
        receive_data.pop('attr_list')
        receive_data.pop('img_list')
        return attr_list, img_list

    def create(self, validated_data):
        # 1，对接收数据的处理和调整
        attr_list, img_list = self.processing_data(validated_data)
        # 2，创建属性
        result = []
        for attr, img in zip(attr_list, img_list):
            attr['image'] = img
            validated_data = attr
            instance = super().create(validated_data)
            result.append(instance)
        return result


class CategoryIndexSerializer(serializers.ModelSerializer):
    """首页分类及显示下面的产品"""

    class Meta:
        model = GoodsCategory
        fields = ["id", "name", ]


class GoodsSearchSerializer(serializers.ModelSerializer):
    """搜索列表"""

    class Meta:
        model = Goods
        fields = ["id", "name", "goods_front_image", "market_price", "shop_price", "sold_num"]


class OptGoodsSerializer(serializers.ModelSerializer):
    """左侧栏可选商品"""
    checked = serializers.BooleanField(default=False, label='是否选中', read_only=True)

    class Meta:
        model = Goods
        fields = ["id", "goods_front_image", "name", "checked"]


class NewGoodsSerializer(serializers.ModelSerializer):
    """新品专享榜"""
    goods_list = serializers.ListField(write_only=True, required=True, label='商品组合')
    name = serializers.CharField(read_only=True, label='商品名')
    goods_front_image = serializers.ImageField(read_only=True, label='封面图')
    market_price = serializers.FloatField(read_only=True, label='市场价')
    shop_price = serializers.FloatField(read_only=True, label='店铺价')
    sold_num = serializers.IntegerField(read_only=True, label='销量')
    is_new = serializers.BooleanField(read_only=True, label='是否新品')

    class Meta:
        model = Goods
        fields = ["id", "name", "goods_front_image", "market_price", "shop_price", "sold_num", "is_new", "goods_list"]


class HotGoodsSerializer(serializers.ModelSerializer):
    """热销榜"""
    goods_list = serializers.ListField(write_only=True, required=True, label='商品组合')
    name = serializers.CharField(read_only=True, label='商品名')
    goods_front_image = serializers.ImageField(read_only=True, label='封面图')
    market_price = serializers.FloatField(read_only=True, label='市场价')
    shop_price = serializers.FloatField(read_only=True, label='店铺价')
    sold_num = serializers.IntegerField(read_only=True, label='销量')
    is_hot = serializers.BooleanField(read_only=True, label='是否热销')

    class Meta:
        model = Goods
        fields = ["id", "name", "goods_front_image", "market_price", "shop_price", "sold_num", "is_hot", "goods_list"]


class HighpointGoodsSerializer(serializers.ModelSerializer):
    """高端榜"""
    goods_list = serializers.ListField(write_only=True, required=True, label='商品组合')
    name = serializers.CharField(read_only=True, label='商品名')
    goods_front_image = serializers.ImageField(read_only=True, label='封面图')
    market_price = serializers.FloatField(read_only=True, label='市场价')
    shop_price = serializers.FloatField(read_only=True, label='店铺价')
    sold_num = serializers.IntegerField(read_only=True, label='销量')
    is_highpoint = serializers.BooleanField(read_only=True, label='是否高端')

    class Meta:
        model = Goods
        fields = ["id", "name", "goods_front_image", "market_price", "shop_price", "sold_num", "is_highpoint",
                  "goods_list"]


class GoodsBannerSerializer(serializers.ModelSerializer):
    """首页轮播的产品名称"""

    class Meta:
        model = Goods
        fields = ["name"]


class BannerSerializer(serializers.ModelSerializer):
    """首页轮播图"""
    goods = GoodsBrandSerializer(read_only=True)
    goods_id = serializers.IntegerField(write_only=True, label='商品id')

    class Meta:
        model = Banner
        fields = ["id", "goods", "goods_id", "image"]


class SearchAdSerializer(serializers.ModelSerializer):
    """搜索框下方广告"""

    class Meta:
        model = SearchAd
        fields = ["id", "title", "image"]


class HotWordsSerializer(serializers.ModelSerializer):
    """热搜词"""

    class Meta:
        model = HotSearchWords
        fields = ["id", "keywords", "index"]


class DiscountGoodsSerializer(serializers.ModelSerializer):
    """优惠套餐产品显示"""

    class Meta:
        model = Goods
        fields = ["id", "name", "goods_front_image", "market_price", "shop_price", "goods_status"]


class DiscountPackageSerializer(serializers.ModelSerializer):
    """优惠套餐"""
    goods = DiscountGoodsSerializer(many=True, read_only=True)
    goods_list = serializers.ListField(write_only=True, required=True, label='商品组合')

    class Meta:
        model = DiscountPackage
        fields = ["id", "name", "image", "goods", "saved_at_most", "start_time", "end_time", "is_valid", "goods_list"]

    def create(self, validated_data):
        validated_data['goods'] = validated_data.get('goods_list')
        validated_data.pop('goods_list')
        return super().create(validated_data)

    def update(self, instance, validated_data):
        validated_data['goods'] = validated_data.get('goods_list')
        validated_data.pop('goods_list')
        return super().update(instance, validated_data)


class CartGoodsShowSerializer(serializers.ModelSerializer):
    """商品显示"""

    class Meta:
        model = Goods
        fields = ["id", "name", "goods_front_image", ]


class CartReSerializer(serializers.ModelSerializer):
    """购物车商品推荐"""
    goods = CartGoodsShowSerializer(read_only=True)
    goods_list = serializers.ListField(write_only=True, required=True, label='商品组合')

    class Meta:
        model = CartRe
        fields = ["id", "show_status", "goods", "goods_list"]

    def create(self, validated_data):
        validated_data['goods'] = validated_data.get('goods_list')[0]
        validated_data.pop('goods_list')
        return super().create(validated_data)


class GoodsListSerializer(serializers.ModelSerializer):
    """商品列表"""
    storage_amout = serializers.SerializerMethodField(label='库存量')

    class Meta:
        model = Goods
        fields = ["id", "name", "start_time", "end_time", "shop_price", "storage_amout", "sold_num", "ship_free",
                  "goods_sn",
                  "goods_status", ]

    def get_storage_amout(self, obj):
        """固定写法:get_+额外添加的字段名,obj代表Goods实例对象"""
        attr = GoodsAttribute.objects.filter(goods=obj.id)
        result = sum([i.storage_amout for i in attr])
        return result


class GoodsSerializer(serializers.ModelSerializer):
    """商品"""
    category_id = serializers.IntegerField(required=True, label="分类ID", help_text="分类ID")
    brand_id = serializers.IntegerField(required=True, label="品牌ID", help_text="品牌ID")
    create_time, update_time = time_format()

    class Meta:
        model = Goods
        exclude = ["category", "brand", ]

